package com.orientation.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.orientation.commom.exception.CustomException;
import com.orientation.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description:
 * @PROJECT_NAME: orientation
 * @PACKAGE_NAME: com.orientation.controller
 * @NAME: FileNewController
 * @author:xuandian
 * @Version: 1.0
 * @DATE: 2021/12/19 17:05
 */
@RestController
@Slf4j
@RequestMapping("/files")
public class FileNewController {

    @Value("${file.upload-path}")
    private String uploadPath;
    @Resource
    private UserService userService;

    /**
     * 上传接口
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/files/" + flag + "_" + originalFilename;  // 获取上传的路径
//        String rootFilePath =uploadPath + flag + "_" + originalFilename;  // 获取上传的路径

        FileUtil.writeBytes(file.getBytes(), rootFilePath);  // 把文件写入到上传的路径
        return "http://localhost:9998/files/" + flag;  // 返回结果 url
//        return "http://localhost:9998/uploadfile/" + flag;  // 返回结果 url
    }

    /**
     * 富文本文件上传接口
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/editor/upload")
    public JSON editorUpload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/files/" + flag + "_" + originalFilename;  // 获取上传的路径
//        String rootFilePath = uploadPath + flag + "_" + originalFilename;  // 获取上传的路径
        FileUtil.writeBytes(file.getBytes(), rootFilePath);  // 把文件写入到上传的路径
        String url = "http://localhost:9998/files/" + flag;
//        String url = "http://localhost:9998/uploadfile/" + flag;
        JSONArray arr = new JSONArray();
        JSONObject data = new JSONObject();
        arr.add(data);
        data.set("url", url);
        return arr;  // 返回结果 url
    }

    /**
     * 下载接口
     *
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/files/";  // 定于文件上传的根路径
//        String basePath = uploadPath;  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            throw new CustomException("18", "文件下载失败");
        }
    }
    ///头像操作  xadxxxxx

    /**
     * 获取模板
     *
     * @param response
     */
    @ApiOperation("模板下载")
    @GetMapping("/template")
    public void downTemp(HttpServletResponse response) throws IOException {
        org.springframework.core.io.ClassPathResource classPathResource = new ClassPathResource("static/template/newStudent.xlsx");
        OutputStream os;
        response.addHeader("Content-Disposition", "attachment;filename=student.xlsx");
        response.setContentType("application/octet-stream");
        byte[] bytes = FileUtil.readBytes(classPathResource.getPath());
        os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }

    @ApiOperation("图片上传")
    @PostMapping("/uploadmaig")
    public void insertImage(MultipartFile file, @RequestParam String loginName, HttpServletRequest request) throws IOException {

        if (file == null) {
            throw new CustomException("18", "请选择新图片");
        }
        String end = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //转换为小写
        String suffix = end.toLowerCase();
        System.out.println(end);
        if (!suffix.equals(".jpg") && !suffix.equals(".jpeg") && !suffix.equals(".png")/* || suffix.equals(".gif")*/) {
            throw new CustomException("18", "文件格式不对，请重新选择");
        }
        //文件名先产生一个uuid 在和真是文件名拼接起来，防止文件重复上传失败
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
        // 得到文件存取位置
        File savePathFile = new File(uploadPath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //保存
        try {
            //将文件保存指定目录
            file.transferTo(new File(uploadPath + fileName));
        } catch (Exception e) {
            log.error("保存文件异常{}", e);
            e.printStackTrace();
            throw new CustomException("18", "保存文件异常");
        }
        //项目url，这里可以使用常量或者去数据字典获取相应的url前缀；
        String fileUrl = "http://localhost:9998";
        //文件获取路径
        fileUrl = fileUrl + "/uploadfile/" + fileName;
        //入库操作
        userService.updateMy(loginName, null, null, null, fileUrl);
    }
}
